
import _ from 'lodash'

export const combineQuery = ({ current, pageSize, query, orderBy, reverse, ...params }) => {
    let res = {}
    if (current !== undefined) {
        res = {
            ...res,
            pagination: {
                current: current - 0,
                pageSize: pageSize - 0,
            }
        }
    }
    if (orderBy !== undefined) {
        res = {
            ...res,
            sorter: {
                orderBy,
                reverse: reverse - 0,
            }
        }
    }
    if (query !== undefined) {
        res = {
            ...res,
            query,
            searchQuery: query,
        }
    }
    return {
        ...params,
        ...res,
    }
}


export const splitQuery = ({ pagination, sorter, searchQuery, ...params }) => {
    let res = {}
    if (pagination) {
        res = {
            ...res,
            current: pagination.current + '',
            pageSize: pagination.pageSize + '',
        }
    }
    if (sorter) {
        res = {
            ...res,
            orderBy: sorter.orderBy,
            reverse: sorter.reverse + ''
        }
    }
    if (searchQuery !== undefined) {
        res = {
            ...res,
            query: searchQuery,
        }
    }
    return {
        ...params,
        ...res
    }
}

export const setQuery = (query, history) => {
    history.replace(`${history.location.pathname}${jsonToUrlSearch(query)}`)
}

export const getQuery = (history) => {
    const { search } = history.location
    return urlSearchToJson(search)
}

export const handleQueryEqual = (query, history) => _.isEqual(query, getQuery(history))

const urlSearchToJson = search => {
    let json = {}
    search.replace('?', '').split('&').map(item => {
        let [key, value] = item.split('=')
        json[key] = (!value || isNaN(value)) ? decodeURIComponent(value) : parseFloat(value)
    })
    return json
}

const jsonToUrlSearch = json => {
    let searchArr = []
    for (let key in json) {
        searchArr.push(`${key}=${json[key]}`)
    }
    return `?${searchArr.join('&')}`
}

export const getHistoryMatchParams = props => {
    const { match } = props
    let _res = {...(match.params || {})}
    for(let key in _res) {
        _res[key] = _res[key] && !isNaN(_res[key]) && _res[key].length < 8 ? parseFloat(_res[key]) : _res[key]
    }
    return _res
}